#!/usr/bin/python -itt

import sys
import numpy as np

import rlcompleter
import readline
readline.parse_and_bind('tab: complete')

import matplotlib.pyplot as plt
from scipy.interpolate import InterpolatedUnivariateSpline


def interpolate_from_files( filenames , debugging_graphics = False):
    
    if debugging_graphics:
        plt.ion()
        fig = plt.figure()

    splines = []
    x_values = []
    
    for filename in filenames:
        data = readfile( filename)
        x_values += data[:,0].tolist()
        spline = InterpolatedUnivariateSpline(data[:,0],data[:,1])
        splines.append(spline)
        if debugging_graphics:
            plt.plot(data[:,0],data[:,1],'.',label=filename[4:14])
            plt.plot(data[:,0],spline(data[:,0]),':',label=filename[4:14]+'_intpol')
        
        
    x_values = np.array(sorted(list(set(x_values))))
    y_values = np.ones( x_values.shape )    
    for spline in splines:
        y_values *= spline( x_values )
    
    full_spline = InterpolatedUnivariateSpline(x_values,y_values)
    
    if debugging_graphics:
        plt.plot(x_values,y_values, '.:',label="full_spline")
        plt.legend()    
        plt.grid(True)
    
    return full_spline



def readfile(filename):
    
    f = open(filename)
    lines = []

    for index, line in enumerate(f):
        line = line.split()
        if len(line) == 0:
            continue
        if '#' in line[0]:
            continue
        line = map(float, line)
        
        #print index, line
        
        lines.append(line)

    data = np.array(lines)
    return data

def test( filename ):
    data = readfile(filename)
    
    x = data[:,0]
    y = data[:,1]

    plt.ion()
    fig = plt.figure()
    plt.plot(x,y, '.',label="original data")


    spline = InterpolatedUnivariateSpline(x,y)
    xx = np.linspace( x[0], x[-1], len(x)*10)

    plt.plot(xx,spline(xx), ':', label="spline interpolation")


if __name__ == '__main__':
    if len(sys.argv) > 1:
        print ('trying to interpolate %s' % (sys.argv[1],))
        test(sys.argv[1])
    else:
        
        Wavelength_dependency_description_files = [ 
            "../tel_definitions/Transmittance_1439Cones_FACT_bearbeitet.txt",
            "../tel_definitions/fact-pde-1.4V.txt",
            "../tel_definitions/MirrorReflectivity_Lustermann_FACT_bearbeitet.txt" ]
    
        angular_acceptance_files = [
            "../tel_definitions/fact-cones-angular-acceptance.txt" ]
        
        wavelength_efficiency = interpolate_from_files( 
                                    Wavelength_dependency_description_files , True)
        angular_acceptance = interpolate_from_files( angular_acceptance_files, True )
        
